package com.seckill.controller;

import cn.hutool.core.util.StrUtil;
import com.seckill.constants.LoginConstant;
import com.seckill.result.CodeMsg;
import com.seckill.result.Result;
import com.seckill.service.MiaoshaUserService;
import com.seckill.util.RandomValidateCodeUtil;
import com.seckill.vo.LoginVo;
import com.seckill.vo.UserPasswordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author yangjunwei
 * @date 2021/10/29 3:23 下午
 */
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    MiaoshaUserService miaoshaUserService;

    @GetMapping("/to_login")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/do_login")
    @ResponseBody
    public Result<Boolean> login(HttpServletResponse httpServletResponse, HttpSession httpSession, @Validated LoginVo loginVo) {
        //验证码为空
        if (StringUtils.isEmpty(loginVo.getVerify()) || Objects.isNull(httpSession)) {
            return Result.error(CodeMsg.VERIFY_NULL);
        }
        //验证验证码
        String code = httpSession.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY).toString();
        if (!StrUtil.equalsIgnoreCase(code, loginVo.getVerify())) {
            return Result.error(CodeMsg.VERIFY_ERROR);
        }
        boolean login = miaoshaUserService.login(httpServletResponse, loginVo);
        return Result.success(login);
    }

    @PostMapping("/updatePassword")
    public Result<Boolean> updatePassword(HttpServletRequest request, @RequestBody UserPasswordVo userPasswordVo) {
        String paramToken = request.getParameter(LoginConstant.COOKIE_NAME);
        boolean updatePassword = miaoshaUserService.updatePassword(paramToken, userPasswordVo.getUserId(),
            userPasswordVo.getOldPassword(), userPasswordVo.getNewPassword());
        return Result.success(updatePassword);
    }

    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");
            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            //输出验证码图片方法
            randomValidateCode.getRandcode(request, response);
        } catch (Exception e) {
            log.error("生成验证码失败");
        }
    }


}
